﻿using System;
using System.Collections.Generic;
using System.Configuration;
using GroupChat2013.Plugins;
using GroupChat2013.Interface;
using GroupChat2013.Entity;
using GroupChat2013.Common;

namespace GroupChat2013.Logic
{
    /// <summary>
    /// 系统默认上下文引擎
    /// </summary>
    public class DefaultEngine : IEngine
    {
        /// <summary>
        /// 类型查找器
        /// </summary>
        private ITypeFinder TypeFinder;

        /// <summary>
        /// 插件集合
        /// </summary>
        public List<IPlugin> Plugins { get; private set; }

        /// <summary>
        /// 插件上下文
        /// </summary>
        public PluginContext PluginContext { get; private set; }

        /// <summary>
        /// 当前登录用户信息
        /// </summary>
        public UserInfo CurrUserInfo { get; set; }

        /// <summary>
        /// 聊天会话管理
        /// </summary>
        public ChatManager ChatManager { get; private set; }

        private FilePathManager _FilePathManager;
        /// <summary>
        /// 文件路径管理
        /// </summary>
        public FilePathManager FilePathManager
        {
            get
            {
                if (_FilePathManager == null)
                {
                    if (CurrUserInfo == null)
                    {
                        throw new Exception("请先设置当前用户");
                    }

                    _FilePathManager = new FilePathManager(CurrUserInfo.UserId, null);
                }

                return _FilePathManager;
            }
        }

        /// <summary>
        /// 聊天配置
        /// </summary>
        public ParseConfig<ChatConfigInfo> ChatConfig { get; set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        public DefaultEngine()
        {
            TypeFinder = new WinAppTypeFinder();
            PluginContext = new PluginContext();
            ChatManager = new ChatManager();
        }

        /// <summary>
        /// 初始化插件，需要继承IStartupTask接口
        /// </summary>
        private void InitPlugIn()
        {
            var pluginsTypes = TypeFinder.FindClassesOfType<IPlugin>();
            var plugins = new List<IPlugin>();
            foreach (var pluginsType in pluginsTypes)
                plugins.Add((IPlugin)Activator.CreateInstance(pluginsType));

            //排序
            plugins.Sort((x, y) => { return x.Order - y.Order; });
            Plugins = plugins;
        }

        public void Initialize()
        {
            //初始化插件
            InitPlugIn();
        }
    }
}
